import tkinter as tk
from tkinter import ttk
#from 文件操作 import db
from 功能窗口 import Insert_Frame, Delete_Frame, Updata_Frame, Mass_import,Export,Check_Frame
from 数据库的连接与使用 import Connect

tables = {
    "员工": ["员工编号", "员工姓名", "员工密码", "员工级别", "员工电话", "员工工资", "备注"],
    "供应商": ["供应商编号", "供应商名称", "供应商简称", "地址", "公司电话", "邮件", "联系人电话", "备注"],
    "商品": ["商品编号", "商品名称", "商品单价", "供应商编号", "商品简介", "备注"],
    "采购主表": ["采购清单号", "员工编号", "采购数量", "采购总价", "采购时间", "备注"],
    "采购明细": ["采购明细号", "采购清单号", "商品编号", "采购数量", "商品单价", "商品总价", "备注"]
}


class Fun_Frame(tk.Frame):
    def __init__(self, root, table):
        super().__init__(root)
        self.table_name = table  # 保存表名
        self.table_view = tk.Frame(self)  # 纸面创建
        self.table_view.pack(fill=tk.BOTH, expand=True)  # 绑定
        self.tree_view = None
        self.page_create()

    def page_create(self):
        # 属性组
        columns = tables[self.table_name]
        # 显示表
        self.tree_view = ttk.Treeview(self.table_view, show='headings', columns=columns)
        # 列宽&对齐方式
        for col in columns:
            self.tree_view.column(col, width=100, anchor='center')
            self.tree_view.heading(col, text=col)

        self.tree_view.pack(fill=tk.BOTH, expand=True)

        # 按键框架
        button_frame = tk.Frame(self)
        button_frame.pack(side=tk.BOTTOM, fill='x')

        # 导入
        tk.Button(button_frame, text='大量导入', command=lambda: Mass_import(self.tree_view, name="添加", columns=columns, table=self.table_name)).pack(side=tk.LEFT, padx=20, pady=5)
        #导出
        tk.Button(button_frame, text='导出',command=lambda: Export(self.tree_view,table_name=self.table_name)).pack(side=tk.LEFT, padx=20, pady=5)
        # 添加
        tk.Button(button_frame, text='添加', command=lambda: Insert_Frame(self.tree_view, name="添加", columns=columns, table=self.table_name)).pack(side=tk.LEFT, padx=20, pady=5)
        # 删除
        tk.Button(button_frame, text='删除', command=lambda: Delete_Frame(self.tree_view, name="删除", table=self.table_name)).pack(side=tk.LEFT, padx=20, pady=5)
        # 修改
        tk.Button(button_frame, text='修改信息', command=lambda: Updata_Frame(self.tree_view, name="修改", columns=columns, table=self.table_name)).pack(side=tk.LEFT, padx=20, pady=5)
        # 刷新
        tk.Button(button_frame, text='刷新', command=self.show_data_frame).pack(side=tk.LEFT, padx=20, pady=5)
        # 查询
        tk.Button(button_frame, text='查询数据', command=lambda: Check_Frame(self.tree_view,table_name=self.table_name)).pack(side=tk.LEFT, padx=20, pady=5)

        # 初始填充数据
        self.show_data_frame()

    def show_data_frame(self):
        # 清空现有数据
        self.tree_view.delete(*self.tree_view.get_children())

        # 从数据库获取数据
        conn = Connect()
        data = conn.select(self.table_name)
        #显示
        if not data:
            return
        for index,row in enumerate(data):
            self.tree_view.insert('',index+1,values=(row))


